# -*- coding: utf-8 -*-

#!/usr/bin/python
# -*- coding: utf-8 -*

import paho.mqtt.client as mqtt
import json
import time
import sqlsave


load = {}
#ab = []
def gettime():
    time1=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    return time1

# 服务器地址
host = 'broker.emqx.io'
# 通信端口 默认端口1883
port = 1883


#username = 'username '
#password = 'password '

# 订阅主题名
topic = 'test_topic'


# 连接后事件
def on_connect(client, userdata, flags, respons_code):
    if respons_code == 0:
        # 连接成功
        print('Connection Succeed!')
    else:
        # 连接失败并显示错误代码
        print('Connect Error status {0}'.format(respons_code))
    # 订阅信息
    client.subscribe(topic)


# 接收到数据后事件
def on_message(client, userdata, msg):
    #打印订阅消息主题
    print("topic", msg.topic)


    # 打印消息数据
    # 补充内容
    jsondata = json.loads(msg.payload)
    load = jsondata["msg"]
    a = load["a"]
    b = load["b"]
    #ab = [a,b]
    # print(msg.payload)
    # print("msg payload", jsondata)
    # print(a,b)
    return a,b

def main():
    client = mqtt.Client()
    # 注册事件
    client.on_connect = on_connect
    client.on_message = on_message
    # 设置账号密码（如果需要的话）
    #client.username_pw_set(username, password=password)
    # 连接到服务器
    client.connect(host, port=port, keepalive=60)
    # 守护连接状态
    client.loop_forever()
    #return ab


print(time1)



if __name__ == '__main__':
    main()






#MySQL保存




      # DBHOST = 'localhost'
      # DBUSER = 'root'
      # DBPASS = 'guotai'
      # DBNAME = 'mqtt_test'
      #
      # try:
      #     db = pymysql.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBNAME)
      #     print('数据库连接成功!')
      # except pymysql.Error as e:
      #     print('数据库连接失败' + str(e))

      # cur = db.cursor()
      # cur.execute('DROP TABLE IF EXISTS Student')
      # sqlQuery = "CREATE TABLE Student(Name CHAR(20) NOT NULL ,Email CHAR(20),Age int )"

      # cur.execute(sqlQuery)
      #
      # sqlQuery = " INSERT INTO test (Name, Email, Age) VALUE (%s,%s,%s) "
      # value = ('Mike', '123456@163.com', 20)
      #
      # try:
      #     cur.execute(sqlQuery, value)
      #     db.commit()
      #     print('数据插入成功！')
      # except pymysql.Error as e:
      #     print("数据插入失败：" + e)
      #     db.rollback()







